﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace BoringTodo
{
    public class Settings
    {
        public event EventHandler SettingsChanged;

        private bool _enableAutoScreenshot = true;
        public bool EnableAutoScreenshot
        {
            get => _enableAutoScreenshot;
            set
            {
                if (_enableAutoScreenshot != value)
                {
                    _enableAutoScreenshot = value;
                    OnSettingsChanged();
                }
            }
        }

        private int _screenshotIntervalMinutes = Constants.DefaultScreenshotInterval;
        public int ScreenshotIntervalMinutes
        {
            get => _screenshotIntervalMinutes;
            set
            {
                if (value < 1)
                {
                    Logger.Log($"尝试设置无效的截图间隔: {value}分钟, 已重置为默认值: {Constants.DefaultScreenshotInterval}分钟", LogLevel.Warning);
                    value = Constants.DefaultScreenshotInterval;
                }

                if (_screenshotIntervalMinutes != value)
                {
                    _screenshotIntervalMinutes = value;
                    OnSettingsChanged();
                }
            }
        }

        private string _explanationText = Constants.DefaultPrompt;
        public string ExplanationText
        {
            get => _explanationText;
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    Logger.Log("尝试设置空的说明文本，已重置为默认值", LogLevel.Warning);
                    value = Constants.DefaultPrompt;
                }

                if (_explanationText != value)
                {
                    _explanationText = value;
                    OnSettingsChanged();
                }
            }
        }

        private string _monthlyExplanationText = Constants.DefaultMonthlyPrompt;
        public string MonthlyExplanationText
        {
            get => _monthlyExplanationText;
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    Logger.Log("尝试设置空的月报说明文本，已重置为默认值", LogLevel.Warning);
                    value = Constants.DefaultMonthlyPrompt;
                }

                if (_monthlyExplanationText != value)
                {
                    _monthlyExplanationText = value;
                    OnSettingsChanged();
                }
            }
        }

        private bool _minimizeToSystemTray = false;
        public bool MinimizeToSystemTray
        {
            get => _minimizeToSystemTray;
            set
            {
                if (_minimizeToSystemTray != value)
                {
                    _minimizeToSystemTray = value;
                    OnSettingsChanged();
                }
            }
        }

        private bool _startWithWindows = false;
        public bool StartWithWindows
        {
            get => _startWithWindows;
            set
            {
                if (_startWithWindows != value)
                {
                    _startWithWindows = value;
                    OnSettingsChanged();
                    UpdateStartupRegistry();
                }
            }
        }

        // 确保不再显示托盘通知
        private bool _trayNotificationShown = false;
        public bool TrayNotificationShown
        {
            get => _trayNotificationShown;
            set
            {
                if (_trayNotificationShown != value)
                {
                    _trayNotificationShown = value;
                    Properties.Settings.Default.TrayNotificationShown = value;
                    Properties.Settings.Default.Save();
                    OnSettingsChanged();
                }
            }
        }

        private void UpdateStartupRegistry()
        {
            try
            {
                // 创建注册表项来在Windows启动时运行应用程序
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

                if (StartWithWindows)
                {
                    key.SetValue("BoringTodo", Application.ExecutablePath);
                    Logger.Log("已添加应用程序到Windows启动项", LogLevel.Info);
                }
                else
                {
                    key.DeleteValue("BoringTodo", false);
                    Logger.Log("已从Windows启动项移除应用程序", LogLevel.Info);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError("更新Windows启动项失败", ex);
                MessageBox.Show($"无法更新启动设置: {ex.Message}", "设置错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        protected virtual void OnSettingsChanged()
        {
            SettingsChanged?.Invoke(this, EventArgs.Empty);
        }

        public async Task SaveAsync()
        {
            try
            {
                string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Constants.AppDataFolder);
                
                // 确保目录存在
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                    Logger.Log($"创建设置文件夹: {folderPath}", LogLevel.Info);
                }

                string filePath = Path.Combine(folderPath, "settings.json");
                string jsonData = JsonConvert.SerializeObject(this, Formatting.Indented);
                
                await FileUtils.WriteAllTextAsync(filePath, jsonData);
                Logger.Log("设置已保存", LogLevel.Info);
            }
            catch (Exception ex)
            {
                Logger.LogError("保存设置失败", ex);
                MessageBox.Show($"保存设置时发生错误: {ex.Message}", "设置错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void Save()
        {
            try
            {
                string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Constants.AppDataFolder);
                
                // 确保目录存在
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                    Logger.Log($"创建设置文件夹: {folderPath}", LogLevel.Info);
                }

                string filePath = Path.Combine(folderPath, "settings.json");
                string jsonData = JsonConvert.SerializeObject(this, Formatting.Indented);
                
                File.WriteAllText(filePath, jsonData);
                Logger.Log("设置已保存", LogLevel.Info);
            }
            catch (Exception ex)
            {
                Logger.LogError("保存设置失败", ex);
                MessageBox.Show($"保存设置时发生错误: {ex.Message}", "设置错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static async Task<Settings> LoadAsync()
        {
            try
            {
                string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Constants.AppDataFolder, "settings.json");
                
                if (!File.Exists(filePath))
                {
                    Logger.Log("设置文件不存在，使用默认设置", LogLevel.Info);
                    return new Settings();
                }

                string jsonData = await FileUtils.ReadAllTextAsync(filePath);
                Settings settings = JsonConvert.DeserializeObject<Settings>(jsonData);
                
                if (settings == null)
                {
                    Logger.Log("设置文件格式错误，使用默认设置", LogLevel.Warning);
                    return new Settings();
                }
                
                Logger.Log("设置已加载", LogLevel.Info);
                return settings;
            }
            catch (Exception ex)
            {
                Logger.LogError("加载设置失败", ex);
                MessageBox.Show($"加载设置时发生错误: {ex.Message}\n将使用默认设置。", "设置错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return new Settings();
            }
        }

        public static Settings Load()
        {
            try
            {
                string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Constants.AppDataFolder, "settings.json");
                
                if (!File.Exists(filePath))
                {
                    Logger.Log("设置文件不存在，使用默认设置", LogLevel.Info);
                    return new Settings();
                }

                string jsonData = File.ReadAllText(filePath);
                Settings settings = JsonConvert.DeserializeObject<Settings>(jsonData);
                
                if (settings == null)
                {
                    Logger.Log("设置文件格式错误，使用默认设置", LogLevel.Warning);
                    return new Settings();
                }
                
                Logger.Log("设置已加载", LogLevel.Info);
                return settings;
            }
            catch (Exception ex)
            {
                Logger.LogError("加载设置失败", ex);
                MessageBox.Show($"加载设置时发生错误: {ex.Message}\n将使用默认设置。", "设置错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return new Settings();
            }
        }
    }
}
